package com.taikang.hmp.hbusiness.doctor.diabeteslife.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.frame.common.TKException;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.datastructre.support.RequestDto;
import com.taikang.hmp.frame.common.properties.PropertiesHelper;
import com.taikang.hmp.frame.common.tools.MD5Util;
import com.taikang.hmp.frame.common.tools.json.JsonHelper;

/**
 * ClassName: SugarLifeService
 * 
 * @Description: 调取高糖接口
 * @author sunyanming
 * @date 2016年3月22日
 */
public class SugarLifeService {
	private static Logger logger = LoggerFactory
			.getLogger(SugarLifeService.class);
	// 高糖服务地址
	private static final String serverAddress = PropertiesHelper.appHelper.getValue("serverAddress");

//	public static final String serverAddress = "http://139.129.29.11:8090/hdhealth";
//	public static final String serverAddress = "http://192.168.2.56:8080/hdhealth";

	// source资源为diabetes 高糖登陆
	@SuppressWarnings("unchecked")
	public static Dto getlogin(String source, RequestDto requestDto) {
		String registUrl = serverAddress + "/app/doctor/diabetes/login.do";
		Dto paramDto = requestDto.getRequestlist().get(0);
		String method = "login4Doctor";
		Map<String, Object> request = getRequestMaplogin("diabetes", method,paramDto, requestDto);
		JSONObject requestJsonObject = JSONObject.fromObject(request);
		// 调用接口
		String responseJson = httpPost(registUrl, requestJsonObject.toString());
		JSONObject responseJsonObject = JSONObject.fromObject(responseJson);
		// 返回的json-->map
		Map<String, Object> response = (Map<String, Object>) responseJsonObject;
		// 获取高糖uid
		String uid = (String) response.get("uid");
		// 解析map
		List<Map<String, Object>> responseBody = (List<Map<String, Object>>) response
				.get("resultlist");
		String resultCode = (String) response.get("resultcode");
		if (resultCode.trim().equalsIgnoreCase("0")) {
			Dto result = new BaseDto();
			for (Map<String, Object> body : responseBody) {
				result.put("state", body.get("state"));
				result.put("diabetesuid", uid);
			}
			return result;
		} else {
			// Map<String, Object> error = (Map<String, Object>)
			// responseBody.get(
			// 0).get("error");
			// String errorMessage = (String) error.get("errorMessage");
			throw new TKException();
		}
	}
	
		//保存血糖
		@SuppressWarnings("unchecked")
		public static Dto saveSugar(String source, RequestDto requestDto) {
			String registUrl = serverAddress + "/app/doctor/diabetes/sugar.do";
			Dto paramDto = requestDto.getRequestlist().get(0);
			String method = "saveSugar4Doctor";
			Map<String, Object> request = getRequestMapSaveSugar("diabetes", method,paramDto, requestDto);
			JSONObject requestJsonObject = JSONObject.fromObject(request);
			// 调用接口
			String responseJson = httpPost(registUrl, requestJsonObject.toString());
			JSONObject responseJsonObject = JSONObject.fromObject(responseJson);
			// 返回的json-->map
			Map<String, Object> response = (Map<String, Object>) responseJsonObject;
			// 获取高糖uid
			String uid = (String) response.get("uid");
			// 解析map
			List<Map<String, Object>> responseBody = (List<Map<String, Object>>) response
					.get("resultlist");
			String resultCode = (String) response.get("resultcode");
			if (resultCode.trim().equalsIgnoreCase("0")) {
				Dto result = new BaseDto();
				for (Map<String, Object> body : responseBody) {
					result.put("diabetesuid", uid);
					result.put("result", body.get("result"));
					result.put("resultcode", body.get("resultcode"));
				}
				return result;
			} else {
				// Map<String, Object> error = (Map<String, Object>)
				// responseBody.get(
				// 0).get("error");
				// String errorMessage = (String) error.get("errorMessage");
				throw new TKException();
			}
		}
		//得到测量血糖列表
		@SuppressWarnings("unchecked")
		public static Dto getSugarList(String source, RequestDto requestDto) {
			String registUrl = serverAddress + "/app/doctor/diabetes/sugar.do";
			Dto paramDto = requestDto.getRequestlist().get(0);
			String method = "getSugarList4Doctor";
			Map<String, Object> request = getRequestMapGetSugarList("diabetes", method,paramDto, requestDto);
			JSONObject requestJsonObject = JSONObject.fromObject(request);
			// 调用接口
			String responseJson = httpPost(registUrl, requestJsonObject.toString());
			JSONObject responseJsonObject = JSONObject.fromObject(responseJson);
			// 返回的json-->map
			Map<String, Object> response = (Map<String, Object>) responseJsonObject;
			// 获取高糖uid
			String uid = (String) response.get("uid");
			// 解析map
			List<Map<String, Object>> responseBody = (List<Map<String, Object>>) response
					.get("resultlist");
			String resultCode = (String) response.get("resultcode");
			List<Map<String,Object>> sugar = new ArrayList<Map<String,Object>>();
			
			if (resultCode.trim().equalsIgnoreCase("0")) {
				Dto result = new BaseDto();
				for (Map<String, Object> body : responseBody) {
					List<Map<String,Object>> list = (List<Map<String, Object>>) body.get("resultlist");
					for (Map<String, Object> li : list) {
						Map<String,Object> m = new HashMap<String,Object>();
						m.put("timespan", li.get("timespan"));
						m.put("value", li.get("value"));
						m.put("date", li.get("date"));
						m.put("record_id", li.get("record_id"));
						m.put("diabetesuid", uid);
						sugar.add(m);
					}
				}
				Dto dto = new BaseDto();
				dto.put("resultlist", sugar);
				return dto;
			} else {
				Dto result = new BaseDto();
				return result;
			}
		}
		
		//删除测量血糖列表
		@SuppressWarnings("unchecked")
		public static Dto delSugarList(String source, RequestDto requestDto) {
			String registUrl = serverAddress + "/app/doctor/diabetes/sugar.do";
			Dto paramDto = requestDto.getRequestlist().get(0);
			String method = "delSugar4Doctor";
			Map<String, Object> request = getRequestMapdelSugarList("diabetes", method,paramDto, requestDto);
			JSONObject requestJsonObject = JSONObject.fromObject(request);
			// 调用接口
			String responseJson = httpPost(registUrl, requestJsonObject.toString());
			JSONObject responseJsonObject = JSONObject.fromObject(responseJson);
			// 返回的json-->map
			Map<String, Object> response = (Map<String, Object>) responseJsonObject;
			// 获取高糖uid
			String uid = (String) response.get("uid");
			// 解析map
			List<Map<String, Object>> responseBody = (List<Map<String, Object>>) response
					.get("resultlist");
			String resultCode = (String) response.get("resultcode");
			if (resultCode.trim().equalsIgnoreCase("0")) {
				Dto result = new BaseDto();
				for (Map<String, Object> body : responseBody) {
					result.put("result", body.get("result"));
					result.put("resultcode", body.get("resultcode"));
					result.put("diabetesuid", uid);
				}
				return result;
			} else {
				Dto result = new BaseDto();
				return result;
			}
		}

	// 组织登陆json请求报文
	private static Map<String, Object> getRequestMaplogin(String source,
			String method, Dto paramDto, RequestDto requestDto) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("method", method);
		map.put("requestid", "");
		map.put("requestsource", source);
		map.put("sessionid", "");
		map.put("uid", "");
		map.put("version", "1.0");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("username", paramDto.getAsString("username"));
		list.add(m);
		map.put("requestlist", list);
		JSONObject jsonObject = JSONObject.fromObject(map);
		System.out.println(jsonObject.toString());
		System.out.println("-------------------");
		System.out.println(JsonHelper.formatJson(jsonObject.toString()));
		return map;
	}
	
	// 组织保存血糖json请求报文
	private static Map<String, Object> getRequestMapSaveSugar(String source,
			String method, Dto paramDto, RequestDto requestDto) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("method", method);
		map.put("requestid", "");
		map.put("requestsource", source);
		map.put("sessionid", "");
		map.put("uid", paramDto.getAsString("diabetesuid"));
		map.put("version", "1.0");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("date", paramDto.getAsString("date"));
		m.put("timespan", paramDto.getAsString("timespan"));
		m.put("value", paramDto.getAsString("value"));
		list.add(m);
		map.put("requestlist", list);
		JSONObject jsonObject = JSONObject.fromObject(map);
		System.out.println(jsonObject.toString());
		System.out.println("-------------------");
		System.out.println(JsonHelper.formatJson(jsonObject.toString()));
		return map;
	}
	
	// 获取血糖列表json请求报文
	private static Map<String, Object> getRequestMapGetSugarList(String source,
			String method, Dto paramDto, RequestDto requestDto) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("method", method);
		map.put("requestid", "");
		map.put("requestsource", source);
		map.put("sessionid", "");
		map.put("uid", paramDto.getAsString("diabetesuid"));
		map.put("version", "1.0");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("startdate", paramDto.getAsString("startdate"));
		m.put("enddate", paramDto.getAsString("enddate"));
		list.add(m);
		map.put("requestlist", list);
		JSONObject jsonObject = JSONObject.fromObject(map);
		System.out.println(jsonObject.toString());
		System.out.println("-------------------");
		System.out.println(JsonHelper.formatJson(jsonObject.toString()));
		return map;
	}
	
	// 删除血糖列表json请求报文
	private static Map<String, Object> getRequestMapdelSugarList(String source,
			String method, Dto paramDto, RequestDto requestDto) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("method", method);
		map.put("requestid", "");
		map.put("requestsource", source);
		map.put("sessionid", "");
		map.put("uid", paramDto.getAsString("diabetesuid"));
		map.put("version", "1.0");
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> m = new HashMap<String, Object>();
		m.put("record_id", paramDto.getAsString("record_id"));
		list.add(m);
		map.put("requestlist", list);
		JSONObject jsonObject = JSONObject.fromObject(map);
		System.out.println(jsonObject.toString());
		System.out.println("-------------------");
		System.out.println(JsonHelper.formatJson(jsonObject.toString()));
		return map;
	}
	
	

	public static String httpPost(String url, String jsonStr) {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("jsonStr", jsonStr));
		String checkStr = MD5Util.stringMD5(jsonStr);
		nvps.add(new BasicNameValuePair("checkStr", checkStr));
		return doHttpPost(url, nvps);
	}

	// 辅助函数: 使用 POST 方式发起一个 HTTP 请求, 并返回结果
	private static String doHttpPost(String remoteurl, List<NameValuePair> nvps) {

//		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpClient httpclient = new DefaultHttpClient();
		try {

			logger.info("doHttpPost request:" + nvps);
			HttpPost httpPost = new HttpPost(remoteurl);

			// 解决提交到服务端中文乱码问题
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
//			CloseableHttpResponse response2 = httpclient.execute(httpPost);
			HttpResponse response2 = httpclient.execute(httpPost);

			try {
				HttpEntity entity2 = response2.getEntity();
				String result = EntityUtils.toString(entity2);
				logger.info("doHttpPost result:" + result);
				return result;
			} finally {
				//response2.close();
			}
		} catch (Exception e) {
			String errorMsg = e.getMessage();
			logger.error(errorMsg, e);
			if (e.getCause() != null) {
				errorMsg = e.getCause().getMessage();
			}
			return errorMsg;

		} finally {
//			try {
//				httpclient.close();
//			} catch (IOException e) {
//
//			}
		}

	}
}
